package com.hoshino.momochi.config;

import com.hoshino.momochi.config.Trie.Trie;
import com.hoshino.momochi.model.domain.Blog;
import com.hoshino.momochi.service.BlogService;
import com.hoshino.momochi.service.RedisService;
import com.hoshino.momochi.service.SensitiveWordService;
import com.hoshino.momochi.service.UserService;
import com.hoshino.momochi.util.CodeEnum;
import com.hoshino.momochi.util.SomeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * Springboot 启动 进行 缓存数据 -> redis
 */
@Component
public class CacheLoad implements ApplicationListener<ApplicationReadyEvent> {

    private final String userIndex = "usernames";

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserService userService;

    @Autowired
    private SensitiveWordService sensitiveWordService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private Trie trie;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        List<Blog> blogList = SomeUtils.sortByCreateTime(blogService.findAllBriefBlogs());
        //int listLen = blogList.size();
        //int pageInfo = CodeEnum.BLOGINFO.getCode();
        //int pages = (listLen + pageInfo - 1) / pageInfo;
        //redisService.CacheBlogPage(pages, blogList, pageInfo, CodeEnum.BLOGPREFIX.getMessage()); // 分页
        redisService.CacheBlog(blogList); // 不分页
        // 缓存用户名信息
        List<String> keys = userService.getAllUsername(); // keys
        redisService.CacheUsername(keys, userIndex);
        List<String> word_list = sensitiveWordService.getAllSensitiveWord();
        for (String word : word_list) {
            trie.addWord(word);
        }
    }
}
